package com.cgtong.android.fragment;


import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.cgtong.android.R;
import com.cgtong.android.adapter.CustomFragmentPagerAdapter;
import com.cgtong.android.base.BaseFragment;
import com.cgtong.android.bean.FilterBean;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.widget.BaseDialog;
import com.cgtong.android.widget.SignCalendar;
import com.cgtong.android.widget.VerticalDrawerLayout;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.simple.eventbus.EventBus;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 大家看看
 * by zhuqingchun
 */
public class ShowEverybodyFragment extends BaseFragment {

    @BindView(R.id.effect_flow_layout)
    TagFlowLayout mEffectFlowLayout;
    @BindView(R.id.finish_flow_layout)
    TagFlowLayout mFinishFlowLayout;
    @BindView(R.id.view_pager)
    ViewPager mViewPager;
    @BindView(R.id.latitude_txt)
    TextView mLatitudeTxt;
    @BindView(R.id.longitude_txt)
    TextView mLongitudeTxt;
    @BindView(R.id.confirm_img)
    ImageView mConfirmImg;
    @BindView(R.id.cancel_img)
    ImageView mCancelImg;
    @BindView(R.id.drawer_layout)
    VerticalDrawerLayout mDrawerLayout;
    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.drawer_ll)
    LinearLayout mDrawerLl;
    @BindView(R.id.title_center_txt)
    TextView mTitleCenterTxt;
    @BindView(R.id.title_right_txt)
    TextView mTitleRightTxt;
    @BindView(R.id.begin_time_txt)
    TextView mBeginTimeTxt;
    @BindView(R.id.end_time_txt)
    TextView mEndTimeTxt;
    private String mBeginTime = "";
    private String mEndTime = "";

    private List<Fragment> mFragmentList = new ArrayList<>();

    private int mStatus = 0;//时效状态
    private int mIsExpired = 0;//受理状态

    private String mLatitudeValue;
    private String mLongitudeValue;

    public static ShowEverybodyFragment newInstance() {
        Bundle args = new Bundle();
        ShowEverybodyFragment fragment = new ShowEverybodyFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_show_everybody;
    }

    @Override
    public void initData() {
        mTitleCenterTxt.setText(getString(R.string.title_show_everybody));
        mTitleRightTxt.setVisibility(View.VISIBLE);
        mTitleRightTxt.setText(getString(R.string.title_txt_all));
        mTitleRightTxt.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(getActivity(), R.drawable.ic_arrow_down), null);
        mTitleRightTxt.setCompoundDrawablePadding((int) getResources().getDimension(R.dimen.drawable_padding_arrow_down));
        mTitleRightTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mDrawerLayout.isDrawerOpen()) {
                    mDrawerLayout.closeDrawer();
                } else {
                    mDrawerLayout.openDrawerView();
                }
            }
        });

        initDrawer();
        initViewPager();
    }


    private void initViewPager() {
        String[] titleArray = getResources().getStringArray(R.array.show_everybody_array);
        mFragmentList.add(BrowseProblemFragment.newInstance());
        mFragmentList.add(CountProblemsFragment.newInstance());
        mViewPager.setAdapter(new CustomFragmentPagerAdapter(getChildFragmentManager(), mFragmentList, titleArray));
        mViewPager.setOffscreenPageLimit(2);
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        mTabLayout.setupWithViewPager(mViewPager);
        setUpIndicatorWidth(mTabLayout);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    mTitleRightTxt.setVisibility(View.VISIBLE);
                } else {
                    mTitleRightTxt.setVisibility(View.GONE);

                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                KeyboardUtils.hideSoftInput(getActivity());
            }
        });
    }

    /**
     * 日历
     */
//    private DateFormat monthFormat = new SimpleDateFormat("yyyy-MM", Locale.getDefault());
//    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private void showCalendarDialog(final boolean isBeginTime) {
        BaseDialog.create(getChildFragmentManager())
                .setLayoutRes(R.layout.layout_calendar_dialog)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        final SignCalendar calendar = (SignCalendar) view.findViewById(R.id.calendar);
                        final TextView titleTxt = (TextView) view.findViewById(R.id.tv_title);
                        titleTxt.setText(calendar.getCalendarYear() + "年" + calendar.getCalendarMonth() + "月");
                        calendar.setOnCalendarClickListener(new SignCalendar.OnCalendarClickListener() {
                            @Override
                            public void onCalendarClick(int row, int col, String dateFormat) {
                                LogUtils.d("dateFormat: " + dateFormat);
                                calendar.removeAllMarks();
                                calendar.addMark(dateFormat, 0);
                                if (isBeginTime) {
                                    mBeginTime = dateFormat;
                                } else {
                                    mEndTime = dateFormat;
                                }
                            }
                        });
                        //监听当前月份
                        calendar.setOnCalendarDateChangedListener(new SignCalendar.OnCalendarDateChangedListener() {
                            public void onCalendarDateChanged(int year, int month) {
                                titleTxt.setText(year + "年" + month + "月");
//                                monthStr = year + "-" + (month < 10 ? "0" + month : month);
                            }
                        });
                        view.findViewById(R.id.last_month_img).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                calendar.lastMonth();
                            }
                        });
                        view.findViewById(R.id.next_month_img).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                calendar.nextMonth();
                            }
                        });
                        view.findViewById(R.id.confirm_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (!calendar.hasMarks()) {
                                    return;
                                }
                                if (isBeginTime) {
                                    mBeginTimeTxt.setText(mBeginTime);
                                    mBeginTimeTxt.setTextColor(ContextCompat.getColor(getActivity(), R.color.color_divider_time));
                                } else {
                                    mEndTimeTxt.setText(mEndTime);
                                    mEndTimeTxt.setTextColor(ContextCompat.getColor(getActivity(), R.color.color_divider_time));
                                }
                                dialog.cancel();

                            }
                        });

                        view.findViewById(R.id.cancel_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.cancel();
                            }
                        });

                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false).
                setGravity(Gravity.BOTTOM)
                .show();
    }

    /**
     * 初始化弹窗
     */
    private void initDrawer() {
        final LayoutInflater mInflater = LayoutInflater.from(getActivity());
        final String[] effectStrArray = getResources().getStringArray(R.array.drawer_effect_status_array);
        mEffectFlowLayout.setMaxSelectCount(1);
        TagAdapter<String> mEffectFlowAdapter = new TagAdapter<String>(effectStrArray) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) mInflater.inflate(R.layout.adapter_tv,
                        mEffectFlowLayout, false);
                tv.setText(s);
                return tv;
            }
        };
        mEffectFlowLayout.setAdapter(mEffectFlowAdapter);
        mEffectFlowAdapter.setSelectedList(0);
        mEffectFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                mIsExpired = position;
                return true;
            }
        });
        //-------------
        final String[] finishStrArray = getResources().getStringArray(R.array.drawer_finish_status_array);
        mFinishFlowLayout.setMaxSelectCount(1);
        TagAdapter<String> mFinishFlowAdapter = new TagAdapter<String>(finishStrArray) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) mInflater.inflate(R.layout.adapter_tv,
                        mFinishFlowLayout, false);
                tv.setText(s);
                return tv;
            }
        };
        mFinishFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                mStatus = position;


                return true;
            }
        });
        mFinishFlowAdapter.setSelectedList(0);
        mFinishFlowLayout.setAdapter(mFinishFlowAdapter);

        mDrawerLayout.setDrawerListener(new VerticalDrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                KeyboardUtils.hideSoftInput(getActivity());
            }

            @Override
            public void onDrawerClosed(View drawerView) {
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
    }


    @OnClick({R.id.confirm_img, R.id.cancel_img, R.id.latitude_txt, R.id.longitude_txt, R.id.begin_time_txt, R.id.end_time_txt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.confirm_img:
                EventBus.getDefault().post(new FilterBean(mStatus, mIsExpired, mLongitudeValue, mLatitudeValue, mBeginTime, mEndTime), ConstantManager.FILTER_TAG);

//                ((BrowseProblemFragment) mFragmentList.get(0)).loadDataByFilter(mStatus, mIsExpired, mLatitudeValue, mLongitudeValue);
                mDrawerLayout.closeDrawer();
                break;
            case R.id.cancel_img:
                mDrawerLayout.closeDrawer();
                break;

            case R.id.latitude_txt:
                showEditDialog(0);
                break;
            case R.id.longitude_txt:
                showEditDialog(1);
                break;
            case R.id.begin_time_txt:
                showCalendarDialog(true);
                break;
            case R.id.end_time_txt:
                showCalendarDialog(false);
                break;
            default:
                break;
        }
    }


    private void showEditDialog(final int index) {
        BaseDialog.create(getChildFragmentManager())
                .setLayoutRes(R.layout.layout_edit_dialog)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        final EditText locationEdt = (EditText) view.findViewById(R.id.content_txt);
                        final TextView tipTxt = (TextView) view.findViewById(R.id.msg_txt);
                        locationEdt.postDelayed(new Runnable() {
                            @Override
                            public void run() {

                                KeyboardUtils.showSoftInput(locationEdt);

                            }
                        }, 400);
                        if (index == 0) {
//                            locationEdt.setText(mLatitudeValue);
                            tipTxt.setText(getString(R.string.txt_hint_latitude));
                        } else {
//                            locationEdt.setText(mLongitudeValue);
                            tipTxt.setText(getString(R.string.txt_hint_longitude));
                        }
//                        locationEdt.setSelection(locationEdt.getText().length());
                        view.findViewById(R.id.confirm_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String str = locationEdt.getText().toString().trim();
                                if (TextUtils.isEmpty(str)) {
                                    if (index == 0) {
                                        mLatitudeValue = null;
                                        mLatitudeTxt.setText(getString(R.string.txt_title_latitude));
                                    } else {
                                        mLongitudeValue = null;
                                        mLongitudeTxt.setText(getString(R.string.txt_title_longitude));
                                    }
                                } else {
                                    if (index == 0) {
                                        mLatitudeValue = locationEdt.getText().toString().trim();
                                        mLatitudeTxt.setText(getString(R.string.txt_title_latitude) + locationEdt.getText().toString());
                                    } else {
                                        mLongitudeValue = locationEdt.getText().toString();
                                        mLongitudeTxt.setText(getString(R.string.txt_title_longitude) + locationEdt.getText().toString());
                                    }
                                }
                                KeyboardUtils.hideSoftInput(locationEdt);
                                dialog.cancel();
                            }
                        });
                        view.findViewById(R.id.cancel_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                KeyboardUtils.hideSoftInput(locationEdt);

                                dialog.cancel();
                            }
                        });


                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false).
                setGravity(Gravity.CENTER)
                .setStyle(R.style.CenterDialogTheme)
                .show();
    }

    /**
     * 通过反射修改TabLayout Indicator的宽度（仅在Android 4.2及以上生效）
     */
    public static void setUpIndicatorWidth(TabLayout tabLayout) {
        Class<?> tabLayoutClass = tabLayout.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayoutClass.getDeclaredField("mTabStrip");
            tabStrip.setAccessible(true);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        LinearLayout layout = null;
        try {
            if (tabStrip != null) {
                layout = (LinearLayout) tabStrip.get(tabLayout);
            }
            for (int i = 0; i < layout.getChildCount(); i++) {
                View child = layout.getChildAt(i);
                child.setPadding(0, 0, 0, 0);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    params.setMarginStart(SizeUtils.dp2px(50f));
                    params.setMarginEnd(SizeUtils.dp2px(50f));
                }
                child.setLayoutParams(params);
                child.invalidate();
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

//    @Subscriber(tag = ConstantManager.LOCATION_TAG)
//    private void asyncLocation(BDLocation location) {
//        LogUtils.d("asyncLocation:" + location.getLatitude() + ";" + location.getLongitude());
//        mLatitudeTxt.setText(getString(R.string.txt_title_latitude) + String.valueOf(location.getLatitude()));
//        mLongitudeTxt.setText(getString(R.string.txt_title_longitude) + String.valueOf(location.getLongitude()));
//        mLatitudeValue = String.valueOf(location.getLatitude());
//        mLongitudeValue = String.valueOf(location.getLongitude());
//    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 注册对象
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        // 注销
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


}
